package cn.com.xy.sms.util;

import java.lang.reflect.Method;
import java.util.Random;
import java.util.UUID;

import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.net.BaseHttpRunnable;
import cn.com.xy.sms.sdk.net.util.Signaturer;
import cn.com.xy.sms.sdk.util.StringUtils;

import android.content.Context;
import android.os.Build;
import android.provider.Settings.Secure;

public class UUIDUtils {

    private static String uuid = null;

    public static String getCloudUUID() {
        if (uuid != null) {
            return uuid;
        } else {
            uuid = getSystemProperty("ro.aliyun.clouduuid", null); // yunos
            if (uuid == null || uuid.trim().length() == 0) {
                uuid = getSystemProperty("ro.sys.aliyun.clouduuid", null); // meizu etc.
            }
        }
        return uuid;
    }

    public static String getSystemProperty(String key, String defaultValue) {
        try {
            Class<?> SystemProperties = Class.forName("android.os.SystemProperties");
            Method m = SystemProperties.getMethod("get", String.class, String.class);
            String result = (String) m.invoke(null, key, defaultValue);
            return result;
        } catch (Throwable e) {

        }
        return defaultValue;
    }

    /* ������� */
    private static char  x36s[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    /* �����?? */
    private static short len    = 20;

    public static String newId() {
        char chs[] = new char[len];

        /**
         * ���??λ�����??��ϵͳʱ��Ϊ���?? ??6λ��??Ӣ����ĸΪ�����??
         */
        long v = (System.currentTimeMillis() - 936748800000L) >> 1; // 1999-9-9
                                                                    // ????������Ҫ���102??)
        for (int i = 7; i > 0; i--) {
            chs[i] = x36s[(int) (v % 36)];
            v = v / 36;
        }
        chs[0] = x36s[(int) (v % 26) + 10]; // ȷ����һ������ַ���"��ĸ", �Է��һ���̵ı�ʶ��??
        /**
         * ���??2λ�����??��UUIDΪ����, ??6λ��??Ӣ����ĸΪ�����??
         */
        UUID u = UUID.randomUUID();
        v = u.getLeastSignificantBits() ^ u.getMostSignificantBits();
        if (v < 0) {
            v = -v;
        }

        for (int i = 8; i < len; i++) {
            chs[i] = x36s[(int) (v % 36)];
            v = v / 36;
        }

        return new String(chs);
    }
    /*SDK-431 songzhirong 20160530 start*/
    /**
     * 生成唯一ID
     * @return
     */
    public static String uniqId(){
        String uniqId = "";
//        long start = System.currentTimeMillis();
        try {
            String imei = BaseHttpRunnable.getDeviceId(false);
            if(imei!=null && !"".equals(imei.trim())){
                uniqId = imei+System.nanoTime()+String.valueOf(new Random().nextInt(1000000000));
            }else{
                uniqId = System.nanoTime()+String.valueOf(new Random().nextInt(1000000000));
            }
        } catch (Throwable e) {
            // TODO: handle exception
        }     
//        long end = System.currentTimeMillis();
//        LogManager.d("uniqId", "uniqId time ="+(end-start));
        return uniqId;
    } 
    /*SDK-431 songzhirong 20160530 end*/
    
    /* SDK-428 huangzhiqiang 20160601 start */
    private static String mUniqueCode = null;
    public static String getUniqueCode() {
        if(!StringUtils.isNull(mUniqueCode)){
            return mUniqueCode;
        }

        String uniqueCode = BaseHttpRunnable.getDeviceId(true);
        if (StringUtils.isNull(uniqueCode)) {
            uniqueCode = SysParamEntityManager.getStringParam(Constant.getContext(), Constant.UNIQUE_CODE);
            if (StringUtils.isNull(uniqueCode)) {
                uniqueCode = Signaturer.sha256Encode(UUID.randomUUID().toString().toUpperCase());
                SysParamEntityManager.setParam(Constant.UNIQUE_CODE, uniqueCode);
            }
        }
        mUniqueCode = uniqueCode;
        return uniqueCode;
    }
    /* SDK-428 huangzhiqiang 20160601 end */
    
    /* SDK-602 zhaojiangwei 20160908 start */
    public static String getUniquePsuedoID() {
		String serial = null;
		String m_szDevIDShort = "";
		try {
			m_szDevIDShort = "35" + Build.BOARD.length() % 10 + Build.BRAND.length() % 10 + Build.CPU_ABI.length() % 10
					+ Build.DEVICE.length() % 10 + Build.DISPLAY.length() % 10 + Build.HOST.length() % 10
					+ Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 + Build.MODEL.length() % 10
					+ Build.PRODUCT.length() % 10 + Build.TAGS.length() % 10 + Build.TYPE.length() % 10
					+ Build.USER.length() % 10; // 13 位
			serial = android.os.Build.class.getField("SERIAL").get(null).toString();
			// API>=9 使用serial号
			return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
		}
		catch (Throwable exception) {
			// serial需要一个初始化
			serial = "microfountain";
		}
		try {
			return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
		}
		catch (Throwable e) {
			// TODO: handle exception
		}
		// 使用硬件信息拼凑出来的15位号码
		return "";
    }
    
    public static String getAndroidId(){
    	String aId = "microfountain";
    	try {
        	Context context = Constant.getContext();
        	if (context!=null) {
        		aId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
    		}	
		}
		catch (Throwable e) {
			// TODO: handle exception
		}
    	return aId;
    }
    /* SDK-602 zhaojiangwei 20160908 end */

}